package com.csthink.mr.combiner;

import com.csthink.mr.wordcount.WordCountMapper;
import com.csthink.mr.wordcount.WordCountReducer;
import com.csthink.utils.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * @author <a href="mailto:csthink@icloud.com">Mars</a>
 * @since 2024-04-12 17:02
 */
public class WordCountDriverWithCombiner {

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        String input = "data/wc.txt";
        String output = "out";

        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);

        FileUtils.deleteIfExists(conf, output);

        // 设置 Job 运行的主类，注意这里必须设置，否则集群中运行会报错，找不到主类
        job.setJarByClass(WordCountDriverWithCombiner.class);

        job.setMapperClass(WordCountMapper.class);
        job.setReducerClass(WordCountReducer.class);
        // 可以自定义 Combiner，也可以直接使用现有的 Reducer，业务逻辑是一样的，注意由于 Combiner 是在 Mapper 端执行，对每个 MapTask
        // 的输出结果做预计算，对于某些场景比如求平均数是不适用的，会导致结果计算错误
        //job.setCombinerClass(WordCountCombiner.class);
        job.setCombinerClass(WordCountReducer.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        // 设置输入路径(可以是文件或者目录)
        //TextInputFormat.setInputPaths(job, new Path(input));
        FileInputFormat.setInputPaths(job, new Path(input));
        FileOutputFormat.setOutputPath(job, new Path(output));

        boolean result = job.waitForCompletion(true);
        System.exit(result ? 0 : 1);

    }
}
